<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
// import { getTableListApi, saveTableApi, delTableListApi } from '@/api/table'
import { useTable } from '@/hooks/web/useTable'
import { useSearch } from '@/hooks/web/useSearch'
import { ref, reactive } from 'vue'
import Detail from './components/Detail.vue'
// import Detail from './components/Detail.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
// import { departmentMap } from '../../../../public/department'

import type { CodeListResponseData, CodeInfo } from '@/api/bianmafuma/type'
//引入获取任务的请求的方法
import { reqCodeList, deleteCode, reqDeleteCodeList } from '@/api/bianmafuma'
import { onMounted } from 'vue'
import { ElTabs, ElTabPane, TabPaneName, ElMessageBox, ElMessage } from 'element-plus'
import { useUserStore } from '@/store/modules/user'
import { inject } from 'vue'

const  departmentMap  = inject<any>('departmentMap')

const userStore = useUserStore()

// const normalDepartment = ref<string>('all')
// const cancelDepartment = ref<string>('all')

const { searchRegister, searchMethods } = useSearch()
const { setValues } = searchMethods

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    let res: CodeListResponseData
    switch (activeName.value) {
      case 'normal':
        res = await reqCodeList(searchValue.value, currentPage.value, pageSize.value)
        break
      case 'cancel':
        res = await reqDeleteCodeList(searchValue.value, currentPage.value, pageSize.value)
        break
      default:
        res = await reqCodeList(searchValue.value, currentPage.value, pageSize.value)
        break
    }

    return {
      list: res.data.list,
      total: res.data.total
    }
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState

const prePage = ref(1)
const prePageSize = ref(10)

const { getList, refresh } = tableMethods

const preSearchValue = ref('all')
const searchValue = ref('all')
searchValue.value = userStore.userInfo?.role === 'admin' ? 'all' : userStore.userInfo!.username
const activeName = ref('normal')

const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index',
    align: 'center',
    search: { hidden: true }
  },
  {
    field: 'code',
    label: '统一识别代码',
    align: 'center',
    search: { hidden: true }
  },
  {
    field: 'entityId',
    label: '实体业务ID',
    align: 'center',
    search: { hidden: true }
  },
  {
    field: 'entityName',
    label: '实体名称',
    align: 'center',
    search: { hidden: true }
  },
  {
    field: 'typeName',
    label: '分类名称',
    align: 'center',
    search: { hidden: true }
  },
  {
    field: 'department',
    label: t('tableDemo.department'),
    align: 'center',
    search: {
      component: 'Select',
      componentProps: {
        options: [{ label: '所有部门', value: 'all' }].concat(
          Object.keys(departmentMap).map((key: string) => {
            return {
              label: departmentMap[key],
              value: key
            }
          })
        ),
        on: {
          change: (value: string) => {
            console.log(value)
            searchValue.value = value
            refresh()
          }
        },
        clearable: false,
        disabled: userStore.userInfo?.role !== 'admin',
      }
    },
    table: {
      formatter: (row: any) => departmentMap[row.department] || '-'
    }
  },
  {
    field: 'registerTime',
    label: '编码时间',
    align: 'center',
    search: { hidden: true },
    form: {
      component: 'DatePicker',
      componentProps: { type: 'datetime', valueFormat: 'YYYY-MM-DD HH:mm:ss' }
    },
    table: {
      // 在表格中显示时间，确保时间格式正确
      formatter: (row: any) => {
        return row.registerTime ? new Date(row.registerTime).toLocaleString('zh-CN', { timeZone: 'UTC' }) : '-'
      }
    }
  },
  {
    field: 'action',
    width: '260px',
    label: t('tableDemo.action'),
    align: 'center',
    search: { hidden: true },
    form: { hidden: true },
    table: {
      fixed:'right',
      width: '200',
      slots: {
        default: (data: any) => (
          <>
            <BaseButton type="primary" onClick={() => action(data.row)}>
              {t('exampleDemo.detail')}
            </BaseButton>
            <BaseButton
              v-show={activeName.value == 'normal'}
              type="danger"
              onClick={() => cancelCode(data.row)}
            >
              注销
            </BaseButton>
          </>
        )
      }
    }
  }
])

// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<CodeInfo | null>(null)

const action = (row: CodeInfo) => {
  dialogVisible.value = true
  dialogTitle.value = '编码详情'
  currentRow.value = row
}

const closeDialog = () => {
  dialogVisible.value = false
  refresh()
}

// 处理标签页切换的回调
const handlePaneChange = (_name: TabPaneName) => {
  // console.log(tab.props.name, event)
  const tmp_page = prePage.value
  const tmp_size = prePageSize.value
  const tmp_search = preSearchValue.value

  prePage.value = currentPage.value
  prePageSize.value = pageSize.value
  preSearchValue.value = searchValue.value

  currentPage.value = tmp_page
  pageSize.value = tmp_size
  searchValue.value = tmp_search

  setValues({
    department: searchValue.value
  })

  getList()
  // switch (tab.props.name) {
  //   case 'normal':
  //     getNormalCodeInfo()
  //     // cancelResTableData.value = []
  //     break
  //   case 'cancel':
  //     getCancelCodeInfo()
  //     // normalResTableData.value = []
  //     break
  // }
}

const cancelCode = (row: CodeInfo) => {
  ElMessageBox.confirm('这条编码将被注销，请确认是否注销?', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      deleteCode(row.code, row.department).then((res) => {
        if (res) {
          getList()
          ElMessage({
            type: 'success',
            message: '注销成功'
          })
        } else {
          ElMessage({
            type: 'error',
            message: '注销失败'
          })
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消注销'
      })
    })
}

const resetSearch = () => {
  searchValue.value = 'all'
  setValues({ department: searchValue.value })
  currentPage.value = 1
  refresh()
}

onMounted(() => {
  setValues({
    department: searchValue.value
  })
})
</script>

<template>
  <ContentWrap>
    <el-tabs @tab-change="handlePaneChange" v-model="activeName">
      <el-tab-pane name="normal" label="正常使用" />
      <el-tab-pane name="cancel" label="已注销" />
    </el-tabs>
    <div style="display: flex; justify-content: space-between">
      <Search
        :schema="allSchemas.searchSchema"
        :show-search="false"
        @reset="resetSearch"
        @register="searchRegister"
      />
    </div>

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      max-height="600"
      headerAlign="center"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle" width="800" maxHeight="400px">
    <Detail :current-row="currentRow!" />

    <template #footer>
      <BaseButton type="danger" @click="closeDialog">关闭</BaseButton>
    </template>
  </Dialog>
</template>
